package com.mall.shopping.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.shopping.IProductService;
import com.mall.shopping.constant.GlobalConstants;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.ItemDesc;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.ItemDescMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements IProductService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;

    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        request.requestCheck();

        ProductDetailResponse productDetailResponse = new ProductDetailResponse();
        productDetailResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        productDetailResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        try {
            Item item = itemMapper.selectByPrimaryKey(request.getId().longValue());
            ProductDetailDto productDetailDto = new ProductDetailDto();
            productDetailDto.setProductId(request.getId().longValue());
            productDetailDto.setProductName(item.getTitle());
            productDetailDto.setSubTitle(item.getSellPoint());
            productDetailDto.setLimitNum(item.getLimitNum() == null ? item.getNum().longValue() : item.getLimitNum().longValue());
            productDetailDto.setSalePrice(item.getPrice());

            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(request.getId().longValue());
            productDetailDto.setDetail(itemDesc.getItemDesc());

            if (StringUtils.isNotBlank(item.getImage())) {
                String images[] = item.getImage().split(",");
                productDetailDto.setProductImageBig(images[0]);
                productDetailDto.setProductImageSmall(Arrays.asList(images));
            }
            productDetailResponse.setProductDetailDto(productDetailDto);
        } catch (Exception e) {
            log.error("ProductServiceImpl.getProductDetail Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(productDetailResponse, e);
        }


        return productDetailResponse;
    }

    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {

        request.requestCheck();

        AllProductResponse allProductResponse = new AllProductResponse();
        allProductResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        allProductResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        // 利用分页插件来分页
        PageHelper.startPage(request.getPage(), request.getSize());

        String orderCol = "created";
        String orderDir = "desc";
        if ("1".equals(request.getSort())) {
            orderCol = "price";
            orderDir = "asc";
        } else if ("-1".equals(request.getSort())) {
            orderCol = "price";
        }

        List<Item> items = null;
        List<ProductDto> productDtos = null;
        PageInfo<Item> itemPageInfo = null;

        //区间搜索,价格最低值
        Integer priceGt = request.getPriceGt();
        if(priceGt == null){
            priceGt = 0;
        }
        //区间搜索,价格最高值
        Integer priceLte = request.getPriceLte();
        if(priceLte == null){
            priceLte = Integer.MAX_VALUE;
        }
        try {
            log.info("start get goods list, condition is " + request);
            items = itemMapper.selectItemFront(request.getCid(), orderCol, orderDir,
                    priceGt, priceLte);

            itemPageInfo = new PageInfo<>(items);
            productDtos = productConverter.items2Dto(items);

        } catch (Exception e) {
            log.error("ProductServiceImpl.getAllProduct Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(allProductResponse, e);
        }
        //log.info("goods list: "+ items.size());
        allProductResponse.setTotal(itemPageInfo.getTotal());
        allProductResponse.setProductDtoList(productDtos);
        return allProductResponse;
    }

    @Override
    public RecommendResponse getRecommendGoods() {

        RecommendResponse recommendResponse = new RecommendResponse();
        recommendResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        recommendResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        // 先查找所有推荐位置的panel

        try {
            List<Panel> panels =
                    panelMapper.selectPanelContentById(GlobalConstants.RECOMMEND_PANEL_ID);
            if (panels == null || panels.isEmpty()) {
                return recommendResponse;
            }

            HashSet panelDtos = new HashSet<>();
            panels.stream().forEach( p -> {
                        List<PanelContentItem> panelContentItems
                            = panelContentMapper.selectPanelContentAndProductWithPanelId(p.getId());

                        PanelDto panelDto = contentConverter.panel2Dto(p);
                        List<PanelContentItemDto> panelContentItemDtos
                                = contentConverter.panelContentItem2Dto(panelContentItems);

                        panelDto.setPanelContentItems(panelContentItemDtos);
                        panelDtos.add(panelDto);
            });
            recommendResponse.setPanelContentItemDtos(panelDtos);
        } catch (Exception e) {
            log.error("ProductServiceImpl.getAllProduct Occur Exception :"+ e);
            ExceptionProcessorUtils.wrapperHandlerException(recommendResponse, e);
        }

        return recommendResponse;
    }

    @Override
    public AllProductResponse searchGoods(SearchProductRequest request) {
        request.requestCheck();

        AllProductResponse allProductResponse = new AllProductResponse();
        allProductResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        allProductResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());


        List<Item> items = null;
        List<ProductDto> productDtos = null;
        PageInfo<Item> itemPageInfo = null;

        Item item = new Item();
        item.setTitle(request.getKey());
        Example example = new Example(item.getClass());
        example.createCriteria().andLike("title","%" + request.getKey() + "%");
        try {
            log.info("search get goods list, condition is " + request);
            items = itemMapper.selectByExample(example);
            itemPageInfo = new PageInfo<>(items);
            productDtos = productConverter.items2Dto(items);

        } catch (Exception e) {
            log.error("ProductServiceImpl.searchProduct Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(allProductResponse, e);
        }

        allProductResponse.setTotal(itemPageInfo.getTotal());
        allProductResponse.setProductDtoList(productDtos);
        return allProductResponse;
    }
}
